package com.baseframe.tool.json.converter;

import com.baseframe.tool.json.module.BaseNumberModule;
import com.baseframe.tool.utils.date.DateUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class BaseMappingApiJackson2HttpMessageConverter extends BaseAbstractReadWriteJackson2HttpMessageConverter{

    @Nullable
    private String jsonPrefix;
    public BaseMappingApiJackson2HttpMessageConverter(ObjectMapper readObjectMapper) {
        super(readObjectMapper,initWriteObjectMapper(readObjectMapper),initMediaType());
    }

    private static ObjectMapper initWriteObjectMapper(ObjectMapper readObjectMapper){
        ObjectMapper writeObjectMapper = readObjectMapper.copy();
        writeObjectMapper.registerModules(BaseNumberModule.INSTANCE);
        return writeObjectMapper;
    }

    private static List<MediaType> initMediaType(){
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(new MediaType("application", "*+json"));
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);

        return supportedMediaTypes;

    }

    @Override
    protected void writeInternal(@NonNull Object object, @Nullable Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        // 如果是字符串，直接写出
        if (object instanceof String) {
//            if (DateUtil.isDate((String) object)){
//
//
//
//            }
            Charset defaultCharset = this.getDefaultCharset();
            Charset charset = defaultCharset == null ? Charsets.UTF_8 : defaultCharset;
            StreamUtils.copy((String) object, charset, outputMessage.getBody());
        } else {
            super.writeInternal(object, type, outputMessage);
        }
    }

    @Override
    protected void writePrefix(@NonNull JsonGenerator generator, @NonNull Object object) throws IOException {
        if (this.jsonPrefix != null) {
            generator.writeRaw(this.jsonPrefix);
        }
    }
}
